<?php

/**

 * 前台登录 退出操作

 *

 *

 *

 * * @网店运维 (c) 2015-2018  Inc. (http://www.shopwwi.com)
 * @license    http://www.shopwwi.c om
 * @link       交流群号：111731672
 * @since      网店运维提供技术支持 授权请购买shopnc授权

 */



//use Shopnc\Tpl;



defined('InShopNC') or exit('Access Invalid!');



class loginControl extends mobileHomeControl {



    public function __construct(){

        parent::__construct();

    }


    /**

     * 登录

     */

    public function indexOp(){
      if (chksubmit()) {
        if(empty($_POST['username']) || empty($_POST['password'])) {
            //output_error('登录失败');
            mobileJump('登录失败', 'index.php');
        }

        $model_member = Model('member');

        $array = array();

        $array['member_name']   = $_POST['username'];

       // $array['member_passwd'] = md5($_POST['password']);

        $member_info = $model_member->getMemberInfo($array);

        if(empty($member_info) && preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $_POST['username'])) {//根据会员名没找到时查手机号

            $array = array();

            $array['member_mobile']   = $_POST['username'];

          //  $array['member_passwd'] = md5($_POST['password']);

            $member_info = $model_member->getMemberInfo($array);

        }

        if(empty($member_info) && (strpos($_POST['username'], '@') > 0)) {//按邮箱和密码查询会员

            $array = array();

            $array['member_email']   = $_POST['username'];

          //  $array['member_passwd'] = md5($_POST['password']);

            $member_info = $model_member->getMemberInfo($array);

        }

        if(!empty($member_info) && $member_info['member_passwd']==md5($_POST['password'])) {
            $_POST['client'] = 'mobile';
            $token = $this->_get_token($member_info['member_id'], $member_info['member_name'], $_POST['client']);

            if($token) {
                //output_data(array('username' => $member_info['member_name'], 'userid' => $member_info['member_id'], 'key' => $token));
                /**
                 * 写入session
                 */
                $_SESSION['is_login'] = '1';
                $_SESSION['is_seller'] = intval($member_info['store_id']) == 0 ? '' : 1;
                $_SESSION['member_id'] = $member_info['member_id'];
                $_SESSION['member_name'] = $member_info['member_name'];
                $_SESSION['member_nickname'] = $member_info['member_nickname'];
                $_SESSION['member_email'] = $member_info['member_email'];
                $_SESSION['member_mobile'] = $member_info['member_mobile'];

                if ($GLOBALS['setting_config']['qq_isuse'] == 1 && trim($member_info['member_qqopenid'])) {
                    $_SESSION['openid'] = $member_info['member_qqopenid'];
                }
                if ($GLOBALS['setting_config']['sina_isuse'] == 1 && trim($member_info['member_sinaopenid'])) {
                    $_SESSION['slast_key']['uid'] = $member_info['member_sinaopenid'];
                }
               setcookie('key',$token,time()+3600*24*365,"/");
                /*检测是否显示现金券红包*/
                mobileJump('登录成功', $_POST['ref_url']);

            } else {
                mobileJump('登录失败', 'index.php');
                //output_error('登录失败');

            }

        }elseif(!empty($member_info)) {
            //查到用户但密码对不上
            mobileJump('用户名密码错误');
        }else {
            mobileJump('用户名不存在');
            //output_error('用户名密码错误');

        }
      }
      if (C('captcha_status_login')) {
            Tpl::output('nchash', substr(md5(SiteUrl . $_GET['act'] . $_GET['op']), 0, 8));
      }
      if(!empty($_SESSION['member_id'])){
          mobileJump('您已登入','index.php');
      }
      if (empty($_GET['ref_url'])) $_GET['ref_url'] = getReferer();
      Tpl::output('html_title', C('site_name') . ' - 登&nbsp;&nbsp;&nbsp;录');
      Tpl::showpage('login');

    }



    /**

     * 登录生成token

     */

    private function _get_token($member_id, $member_name, $client) {

        $model_mb_user_token = Model('mb_user_token');



        //重新登录后以前的令牌失效

        //暂时停用

        //$condition = array();

        //$condition['member_id'] = $member_id;

        //$condition['client_type'] = $client;

        //$model_mb_user_token->delMbUserToken($condition);



        //生成新的token

        $mb_user_token_info = array();

        $token = md5($member_name . strval(TIMESTAMP) . strval(rand(0,999999)));

        $mb_user_token_info['member_id'] = $member_id;

        $mb_user_token_info['member_name'] = $member_name;

        $mb_user_token_info['token'] = $token;

        $mb_user_token_info['login_time'] = TIMESTAMP;

        $mb_user_token_info['client_type'] = $client;



        $result = $model_mb_user_token->addMbUserToken($mb_user_token_info);



        if($result) {

            return $token;

        } else {

            return null;

        }



    }



    /**

     * 注册

     */

    public function registerOp(){
        redirect('index.php?act=register');
      if (chksubmit()) {
          $model_member   = Model('member');
          $mobile = trim($_POST['mobile']);
          if(!empty($mobile) && preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $mobile)){

              if(!empty($_POST['captcha'])){
                  $captcha = trim($_POST['captcha']);
                  if($this->check_captcha($mobile,$captcha)){
                      //注册码验证通过
                      if(C('assign_user_name')){
                          $number = $model_member->getRegisterNum();
                          $NumberLogic = Logic("number");
                          $user_id = substr(date('Ym'),1,5).sprintf("%06s",$number+1);
                          $user_code = $NumberLogic->encodeNum($user_id);
                          $member_name = "JYC".substr($user_code,1);
                      }
                      $passwd = $captcha;
                      $member = $model_member->getMemberInfo(array('member_name'=> $member_name));//检查重名
                      if(!empty($member)) {
                          mobileJump('用户名已被注册','index.php?act=login&op=register');
                      }
                      $member = $model_member->getMemberInfo(array('member_mobile'=> $mobile));//检查手机号是否已被注册
                      if(!empty($member)) {
                          mobileJump('手机号已被注册','index.php?act=login&op=register');
                      }
                      if(C('ucenter_status')) {
                         /* $model_ucenter = Model('ucenter');
                          $remote_member_info = $model_ucenter->getUserInfo(trim($mobile),4);*/
                          $newuc=Model('newuc');
                          $remote_member_info=$newuc->get_uc_user_info(array('user_name'=>$mobile));
                      }
                      if(!empty($remote_member_info)){
                          //UC用户直接写入数据表
                          $member = array();
                          $member['member_id'] = $remote_member_info['uid'];
                          $member['member_name'] = $remote_member_info['username'];
                          $member['member_passwd'] = $remote_member_info['password'];
                          $member['member_mobile'] = $remote_member_info['mobile'];
                          $member['member_email'] = $remote_member_info['email'];
                          $member['member_nickname'] = "u" . substr($mobile, -4);
                          $member['member_mobile_bind'] = 1;
                          $member['plain_passwd'] = 1;
                          $member['member_type'] = $remote_member_info['usertype'];
                          $result = $model_member->addMember($member);
                          if ($result) {
                              $member_name = $remote_member_info['username'];
                              $member = $model_member->getMemberInfo(array('member_name' => $member_name));
                              $model_member->createSession($member, true);//自动登录
                              redirect('index.php?act=login&op=success');
                          }
                      }else {
                          $member = array();
                          $member['member_name'] = $member_name;
                          $member['member_passwd'] = $passwd;
                          $member['member_mobile'] = $mobile;
                          $member['member_email'] = '';
                          $member['member_mobile_bind'] = 1;
                          $member['member_nickname'] = "u".substr($mobile,-4);
                          $member['member_truename'] = trim($_POST['truename']);
                          $member['member_type'] = 2;
                          $result = $model_member->addMember($member);

                          if ($result) {
                              /**
                               * Ucenter处理
                               */
                              if (C('ucenter_status')) {
                                  Language::read("home_login_register");
                                  $lang = Language::getLangContent();
                                  $data = array();
                                  $data['username']=addslashes($_POST['member_name']);
                                  $data['password']=addslashes($_POST['password']);
                                  $data['mobile']=$mobile;
                                  //var_dump($data);exit;
                                  $newuc=Model('newuc');
                                  $uid=$newuc->uc_mobile_reg($data);
                                 /* $model_ucenter = Model('ucenter');
                                  $uid = $model_ucenter->addUser(array('username' => $member_name, 'password' => $passwd, 'mobile' => trim($mobile), 'email' => '', 'member_type' => 2));*/

                                  //if($uid<1) showMessage($lang['login_usersave_regist_fail'],'','html','error');
                              }
                              $member = $model_member->getMemberInfo(array('member_name' => $member_name));
                              $model_member->createSession($member, true);//自动登录
                              redirect('index.php?act=login&op=success');
                          } else {
                              mobileJump('注册失败', 'index.php?act=login&op=register');
                          }
                      }
                  }else{
                      mobileJump('验证码不正确','index.php?act=login&op=register');
                  }
              }else {
                  Tpl::output('mobile', $mobile);
                  Tpl::output('truename', $_POST['truename']);
              }
          }else{
              mobileJump('手机号格式不正确','index.php?act=login&op=register');
          }
      }
      Tpl::output('html_title', C('site_name') . ' - 注&nbsp;&nbsp;&nbsp;册');
      Tpl::showpage('reg');

    }

    /*
     * 矿博会注册页面
     */
    public function kmallOp(){
        Language::read("home_login_register");
        $lang   = Language::getLangContent();
        $model_member   = Model('member');
        if (chksubmit()) {
            $mobile = trim($_POST['mobile']);
            if(!empty($mobile) && preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $mobile)){
                if(!empty($_POST['captcha'])){
                    $captcha = trim($_POST['captcha']);
                    if($this->check_captcha($mobile,$captcha)){
                        //注册码验证通过
                        if(C('assign_user_name')){
                            $number = $model_member->getRegisterNum();
                            $NumberLogic = Logic("number");
                            $user_id = substr(date('Ym'),1,5).sprintf("%06s",$number+1);
                            $user_code = $NumberLogic->encodeNum($user_id);
                            $member_name = "JYC".substr($user_code,1);
                        }
                        $passwd = $captcha;
                        $member = $model_member->getMemberInfo(array('member_name'=> $member_name));//检查重名
                        if(!empty($member)) {
                            mobileJump('用户名已被注册','index.php?act=login&op=kmall');
                        }
                        $member = $model_member->getMemberInfo(array('member_mobile'=> $mobile));//检查手机号是否已被注册
                        if(!empty($member)) {
                            mobileJump('手机号已被注册','index.php?act=login&op=kmall');
                        }
                        if(C('ucenter_status')) {
                           /* $model_ucenter = Model('ucenter');
                            $remote_member_info = $model_ucenter->getUserInfo(trim($mobile),4);*/
                            $newuc=Model('newuc');
                            $remote_member_info=$newuc->get_uc_user_info(array('user_name'=>$mobile));
                        }
                        if(!empty($remote_member_info)){
                            //UC用户直接写入数据表
                            $member = array();
                            $member['member_id'] = $remote_member_info['uid'];
                            $member['member_name'] = $remote_member_info['username'];
                            $member['member_passwd'] = $remote_member_info['password'];
                            $member['member_mobile'] = $remote_member_info['mobile'];
                            $member['member_email'] = $remote_member_info['email'];
                            $member['member_nickname'] = "u" . substr($mobile, -4);
                            $member['member_mobile_bind'] = 1;
                            $member['plain_passwd'] = 1;
                            $member['member_type'] = $remote_member_info['usertype'];

                            $result = $model_member->addMember($member);
                            if ($result) {
                                $member_name = $remote_member_info['username'];
                                $member = $model_member->getMemberInfo(array('member_name' => $member_name));
                                $model_member->createSession($member, true);//自动登录
                                redirect('index.php?act=login&op=resetpwd');
                            }
                        }else {
                            $member = array();
                            $member['member_name'] = $member_name;
                            $member['member_passwd'] = md5($passwd);
                            $member['member_mobile'] = $mobile;
                            $member['member_email'] = '';
                            $member['member_mobile_bind'] = 1;
                            $member['member_nickname'] = "u".substr($mobile,-4);
                            $member['member_type'] = 2;
                            $result = $model_member->addMember($member);

                            if ($result) {
                                /**
                                 * Ucenter处理
                                 */
                                if (C('ucenter_status')) {
                                    Language::read("home_login_register");
                                    $lang = Language::getLangContent();
                                    $data = array();
                                    $data['username']=addslashes($_POST['member_name']);
                                    $data['password']=addslashes($_POST['password']);
                                    $data['mobile']=$mobile;
                                    //var_dump($data);exit;
                                    $newuc=Model('newuc');
                                    $uid=$newuc->uc_mobile_reg($data);
                                   /* $model_ucenter = Model('ucenter');
                                    $uid = $model_ucenter->addUser(array('username' => $member_name, 'password' => $passwd, 'mobile' => trim($mobile), 'email' => '', 'member_type' => 2));*/

                                    //if($uid<1) showMessage($lang['login_usersave_regist_fail'],'','html','error');
                                }
                                $member = $model_member->getMemberInfo(array('member_name' => $member_name));
                                $model_member->createSession($member, true);//自动登录
                                redirect('index.php?act=login&op=success');
                            } else {
                                mobileJump('注册失败', 'index.php?act=login&op=kmall');
                            }
                        }
                    }else{
                        mobileJump('验证码不正确','index.php?act=login&op=kmall');
                    }
                }
               Tpl::output('mobile',$mobile);
            }else{
                mobileJump('手机号格式不正确','index.php?act=login&op=kmall');
            }
        }
        $model_member->checkloginMember();
        Tpl::output('html_title',C('site_name').' - '.$lang['login_register_join_us']);
        Tpl::showpage('mobile_register');
    }

    public function resetpwdOp(){
        Language::read("home_login_register");
        Tpl::showpage('mobile_reset');
    }

    public function successOp(){
        Tpl::showpage('mobile_success');
    }

    public function menpiaoOp(){
        $ref = $_GET['ref'];
        if(empty($_SESSION['member_id'])){
            mobileJump('跳转注册', 'index.php?act=register&op=index&ref='.$ref);
        }
        Tpl::showpage('mobile_menpiao');
    }

    /**
     * 验证注册动态码
     */
    private function check_captcha($phone,$captcha){
        $state = false;
        if (strlen($phone) == 11 && strlen($captcha) == 6){
            $state = 'true';
            $condition = array();
            $condition['log_phone'] = $phone;
            $condition['log_captcha'] = $captcha;
            $condition['log_type'] = 1;
            $model_sms_log = Model('sms_log');
            $sms_log = $model_sms_log->getSmsInfo($condition);
            if(!empty($sms_log) || ($sms_log['add_time'] > TIMESTAMP-1800)) {//半小时内进行验证为有效
                $state = true;
            }
        }
        return $state;
    }

    public function forgetOp(){
        if (chksubmit()) {
           
        }else{
            Tpl::showpage('mobile_forget');
        }
    }


    /**
     * 退出操作
     *
     * @param int $id 记录ID
     * @return array $rs_row 返回数组形式的查询结果
     */
    public function logoutOp(){
        Language::read("home_login_index");
        $lang   = Language::getLangContent();
        $data['uid']=$_SESSION['member_id'];
        // 清理COOKIE
        setNcCookie('msgnewnum'.$_SESSION['member_id'],'',-3600);
        setNcCookie('auto_login', '', -3600);
        setNcCookie('cart_goods_num','',-3600);
        session_unset();
        session_destroy();
        /**
         * 同步登录通知
         */
        /**
         * Ucenter处理
         */

        if(C('ucenter_status')) {
            $newuc=Model('newuc');
            $newuc->synlogout($data);
           /* $model_ucenter = Model('ucenter');
            $out_str = $model_ucenter->userLogout();*/
            $lang['login_logout_success'] = $lang['login_logout_success'].$out_str;
            if(empty($_GET['ref_url'])){
                $ref_url = getReferer();
            }else {
                $ref_url = $_GET['ref_url'];
            }
            mobileJump('登出成功','index.php?act=login&ref_url='.urlencode($ref_url));
        }else{
            redirect();
        }
    }


}

